﻿using System;
using System.Text.RegularExpressions;
using JetBrains.Annotations;

namespace WikiDoc.Lines
{
    /// <summary>
    /// 对应一个 “== xxxx ==” 标题行
    /// </summary>
    public class HeaderLine : WikiLine
    {
        /// <summary>
        /// 标题级别，即等号数量
        /// </summary>
        /// <value>The level.</value>
        public int Level { get; private set; }

        /// <summary>
        /// 标题内容
        /// </summary>
        /// <value>The content.</value>
        public string Content { get; private set; }


        /// <summary>
        /// 初始化 <see cref="HeaderLine"/> 类的新实例.
        /// </summary>
        /// <param name="line"></param>
        /// <param name="level"></param>
        /// <param name="content"></param>
        protected HeaderLine(string line, int level, string content) : base(line, LineTypes.Header)
        {
            if (line == null) throw new ArgumentNullException("line");

            if (content == null) throw new ArgumentNullException("content");

            if (level <= 0)
            {
                throw new ArgumentOutOfRangeException("level", level, "level 必须大于 0");
            }

            Line = line;
            Level = level;
            Content = content;
        }


        /// <summary>
        /// 标题行定义： [若干等号][至少一个空格][标题内容][至少一个空格][若干等号]
        /// </summary>
        public static readonly Regex Pattern = new Regex(
            @"\A \s*  ([=＝]+)(?= [^=＝])  \s*  (.*?)  \s*  (?<= [^=＝])([=＝]+) \s* \z",
            RegexOptions.Compiled |
            RegexOptions.CultureInvariant |
            RegexOptions.Singleline |
            RegexOptions.IgnorePatternWhitespace);

        [CanBeNull]
        public static WikiLine TryParse([CanBeNull] string line)
        {
            if (line == null) return null;

            var match = Pattern.Match(line);

            return match.Success
                       ? new HeaderLine(line,
                                        match.Groups[1].Length,
                                        match.Groups[2].Value)
                       : null;
        }
    }
}
